<template>
  <div class="workorder-detail-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button 
          icon="el-icon-arrow-left" 
          @click="goBack"
          class="back-button">
          返回
        </el-button>
        <div class="page-info">
          <h1 class="page-title">工单详情</h1>
          <p class="page-subtitle">工单编号：{{ workOrderDetail.orderNumber }}</p>
        </div>
      </div>
      <div class="header-right">
        <el-tag type="success" size="medium">已完成</el-tag>
        <el-button size="small" @click="printOrder">打印</el-button>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="content-wrapper">
      <div class="detail-sections">
        
        <!-- 基础信息 -->
        <div class="detail-section">
          <div class="section-header">
            <h3 class="section-title">基础信息</h3>
          </div>
          <div class="section-content">
            <div class="info-grid">
              <div class="info-item">
                <label>工单编号：</label>
                <span>{{ workOrderDetail.orderNumber }}</span>
              </div>
              <div class="info-item">
                <label>故障等级：</label>
                <span>
                  <dict-tag :options="dict.type.gelly_fault_level" :value="workOrderDetail.faultLevel"/>
                </span>
              </div>
              <div class="info-item">
                <label>报告人：</label>
                <span>{{ getUserName(workOrderDetail.reporterId) }}</span>
              </div>
              <div class="info-item">
                <label>发生时间：</label>
                <span>{{ workOrderDetail.occurrenceTime }}</span>
              </div>
              <div class="info-item">
                <label>设备信息：</label>
                <span>{{ workOrderDetail.deviceInfo }}</span>
              </div>
              <div class="info-item">
                <label>异常类型：</label>
                <span>
                  <dict-tag :options="dict.type.gelly_abnormal_type" :value="workOrderDetail.abnormalType"/>
                </span>
              </div>
              <div class="info-item">
                <label>影响轴向：</label>
                <span>{{ workOrderDetail.affectedAxes }}</span>
              </div>
              <div class="info-item full-width">
                <label>异常描述：</label>
                <div class="markdown-content">
                  <MarkdownRenderer
                    :value="workOrderDetail.abnormalDescription || ''"
                    :editable="false"
                    :maxHeight="120"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 故障分析 -->
        <div class="detail-section" v-if="workOrderDetail.faultAnalysis">
          <div class="section-header">
            <h3 class="section-title">故障分析</h3>
          </div>
          <div class="section-content">
            <div class="info-grid">
              <div class="info-item">
                <label>故障描述：</label>
                <span>{{ workOrderDetail.faultAnalysis.faultDescription }}</span>
              </div>
              <div class="info-item full-width">
                <label>故障原因：</label>
                <div class="markdown-content">
                  <MarkdownRenderer
                    :value="workOrderDetail.faultAnalysis.faultCause || ''"
                    :editable="false"
                    :maxHeight="120"
                  />
                </div>
              </div>
              <div class="info-item full-width">
                <label>解决方案：</label>
                <div class="markdown-content">
                  <MarkdownRenderer
                    :value="workOrderDetail.faultAnalysis.solution || ''"
                    :editable="false"
                    :maxHeight="120"
                  />
                </div>
              </div>
              <div class="info-item full-width">
                <label>预防措施：</label>
                <div class="markdown-content">
                  <MarkdownRenderer
                    :value="workOrderDetail.faultAnalysis.preventiveMeasures || ''"
                    :editable="false"
                    :maxHeight="120"
                  />
                </div>
              </div>
              <div class="info-item">
                <label>分析时间：</label>
                <span>{{ workOrderDetail.faultAnalysis.analysisTime }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 处理记录 -->
        <div class="detail-section" v-if="workOrderDetail.handlingProcesses && workOrderDetail.handlingProcesses.length > 0">
          <div class="section-header">
            <h3 class="section-title">处理记录</h3>
          </div>
          <div class="section-content">
            <div class="process-list">
              <div 
                v-for="(process, index) in workOrderDetail.handlingProcesses" 
                :key="process.id"
                class="process-item">
                <div class="process-header">
                  <h4>第{{ index + 1}}次处理</h4>
                  <span class="process-time">{{ process.createTime }}</span>
                </div>
                <div class="process-content">
                  <div class="info-grid">
                    <div class="info-item">
                      <label>处理人员：</label>
                      <span>{{ getUserName(process.handlerId) }}</span>
                    </div>
                    <div class="info-item">
                      <label>预计完成时间：</label>
                      <span>{{ process.estimatedCompletionTime }}</span>
                    </div>
                    <div class="info-item full-width">
                      <label>处理方案：</label>
                      <div class="markdown-content">
                        <MarkdownRenderer
                          :value="process.handlingScheme || ''"
                          :editable="false"
                          :maxHeight="100"
                        />
                      </div>
                    </div>
                    <div class="info-item full-width">
                      <label>处理备注：</label>
                      <div class="markdown-content">
                        <MarkdownRenderer
                          :value="process.handlingNotes || ''"
                          :editable="false"
                          :maxHeight="100"
                        />
                      </div>
                    </div>
                    <div class="info-item">
                      <label>更换零件：</label>
                      <span>{{ process.producedParts }}</span>
                    </div>
                    <div class="info-item">
                      <label>验收结果：</label>
                      <span :class="getAcceptanceClass(process.acceptanceResult)">
                        {{ getAcceptanceText(process.acceptanceResult) }}
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

      </div>
    </div>
  </div>
</template>

<script>
import { getOrderDetail } from '@/api/fault/order';
import { listUser } from '@/api/system/user';

export default {
  name: 'WorkOrderDetail',
  dicts: ['gelly_abnormal_type', 'gelly_fault_level', 'gelly_acceptance_result'],
  data() {
    return {
      workOrderDetail: {
        orderNumber: '',
        faultLevel: 0,
        reporterId: '',
        occurrenceTime: '',
        deviceInfo: '',
        abnormalType: '',
        affectedAxes: '',
        abnormalDescription: '',
        faultAnalysis: null,
        handlingProcesses: []
      },
      userList: [],
      loading: false
    }
  },
  created() {
    console.log('详情页面创建，路由参数:', this.$route.params);
    console.log('完整路由信息:', this.$route);
    this.fetchUserList();
    this.loadWorkOrderDetail();
  },
  methods: {
    async fetchUserList() {
      try {
        const response = await listUser({ pageNum: 1, pageSize: 9999 });
        if (response.code === 200) {
          this.userList = response.rows.map(user => ({
            label: user.userName,
            value: user.userId
          }));
        }
      } catch (error) {
        console.error('获取用户列表失败:', error);
      }
    },
    async loadWorkOrderDetail() {
      const orderId = this.$route.params.id;
      console.log('获取到的工单ID:', orderId);

      if (!orderId) {
        console.error('工单ID不存在');
        this.$message.error('工单ID不存在');
        this.goBack();
        return;
      }

      this.loading = true;
      try {
        const response = await getOrderDetail(orderId);
        if (response.code === 200 && response.data) {
          this.workOrderDetail = response.data;
        } else {
          throw new Error(response.msg || '获取工单详情失败');
        }
      } catch (error) {
        console.error('加载工单详情失败:', error);
        this.$message.error('加载工单详情失败: ' + (error.message || '未知错误'));
      } finally {
        this.loading = false;
      }
    },
    getFaultLevelText(level) {
      const levelMap = {
        0: '低',
        1: '中',
        2: '高',
        3: '紧急'
      };
      return levelMap[level] || '未知';
    },
    getAbnormalTypeText(type) {
      // 这里应该从字典获取，暂时使用简单映射
      const typeMap = {
        0: '机械故障',
        1: '电气故障',
        2: '软件故障',
        3: '其他'
      };
      return typeMap[type] || '未知';
    },
    getAcceptanceText(result) {
      const resultMap = {
        0: '待复检',
        1: '通过',
        2: '不通过'
      };
      return resultMap[result] || '未知';
    },
    getAcceptanceClass(result) {
      const classMap = {
        0: 'acceptance-pass',
        1: 'acceptance-fail',
        2: 'acceptance-pending'
      };
      return classMap[result] || '';
    },
    printOrder() {
      window.print();
    },
    goBack() {
      this.$router.back();
    },
    getUserName(userId) {
      if (!userId || !this.userList) return '未知用户';
      const user = this.userList.find(u => u.value === userId || u.value === String(userId));
      return user ? user.label : `用户${userId}`;
    }
  }
}
</script>

<style scoped>
.workorder-detail-page {
  min-height: 100vh;
  background: #fafbfc;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 14px 20px;
  background: white;
  border-bottom: 1px solid #e8eaec;
  box-shadow: 0 1px 4px rgba(0,0,0,0.04);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.back-button {
  border: none;
  background: #f5f7fa;
  color: #606266;
}

.page-info h1 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.page-info p {
  margin: 4px 0 0 0;
  font-size: 13px;
  color: #909399;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.content-wrapper {
  padding: 20px;
}

.detail-section {
  background: white;
  border-radius: 8px;
  margin-bottom: 16px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.04);
}

.section-header {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f2f5;
}

.section-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.section-content {
  padding: 20px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 16px;
}

.info-item {
  display: flex;
  align-items: flex-start;
}

.info-item label {
  min-width: 100px;
  font-weight: 500;
  color: #606266;
  margin-right: 8px;
}

.info-item span {
  color: #303133;
  word-break: break-word;
}

.info-item.full-width {
  grid-column: 1 / -1;
}

.markdown-content {
  margin-top: 4px;
}

.process-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.process-item {
  border: 1px solid #e8eaec;
  border-radius: 6px;
  overflow: hidden;
}

.process-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f8f9fa;
  border-bottom: 1px solid #e8eaec;
}

.process-header h4 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.process-time {
  font-size: 12px;
  color: #909399;
}

.process-content {
  padding: 16px;
}

.acceptance-pass {
  color: #67c23a;
  font-weight: 500;
}

.acceptance-fail {
  color: #f56c6c;
  font-weight: 500;
}

.acceptance-pending {
  color: #e6a23c;
  font-weight: 500;
}
</style>
